import React, { useLayoutEffect, useRef } from "react";
import { Input } from "antd";
import set from "lodash/set";
import { useFormField } from "../../context/form-context";

import SelectAuditors from "../../../../RuntimeForm/SelectAuditors/SelectAuditors";
import { useInject } from "../../context/inject-context";
import { useForm } from "../MyForm";
import { parseToArray } from "../../utils";

let defaultConfig = {
  //这一批属性来源 tplData.form.data_control （步骤权限）
  // "code": "a3",
  // "name": "选人-无默认值-可编",
  // "type": "select_person",
  // "is_show": true,
  // "is_editable": true,
  // "is_required": false,

  //这一批属性来源 tplData.form.form_meta_data （表单设计器）
  // "isUsed": false,
  // "designProps": {
  //     "code": "a3",
  //     "name": "选人-无默认值-可编",
  //     "ui": "wfd_person",
  //     "title": "选人-无默认值-可编",
  //     "layout": "control_layout_leftRight",
  //     "defaultValue": "default_value",
  //     "text": "请选择选人-无默认值-可编",
  //     "tipstext": "",
  //     "type": "select_person",
  //     "title_w": 85
  // },

  //这一批属性来源 tplData.form.data_define （业务对象）
  // "show_type": "",
  // "show_type_name": "",
  // "is_sys": 0,
  // "isHide": false,
  // "default_value": "[无]",
  // "props": {
  //     "default_value": "default_value"//默认值
  // },
  // "type_name": "人员选择",
  
  //来源 tplData.form.defaultValueConf
  // "default": null
}

export default function ({ id, field, label, rules, showLabel = false, onChange, onBlur, displayFormatter, valueFormatter, required,cell, rowIndex, ...others }) {

  const { data: tplData, urlPrefix, params, csrfToken } = useForm().root;

  const injectInfo = useInject();
  if (injectInfo?.isDefaultRequired === true) {
    rules = [{
        validator(rule, value, callback) {
            if(value === '[]' || value === undefined || value === null || value === ""){//当前值为空数组时，触发校验
                return false;
            }
            return true;
        }
    }];//选人组件需要自定义必填校验
  }

  const { input: fieldConfig, property, validation, readonly, className, isDisplay } = useFormField({
    field,
    rules,
    onChange,
    displayFormatter,
    valueFormatter,
    onBlur,
  });

  let defaultValue = fieldConfig.value;
  if(defaultValue === undefined || defaultValue === null || typeof(defaultValue) !== "string"){//字段值容错处理
    if(cell?.props?.default_value==="current_user"){
        fieldConfig.onChange(JSON.stringify([{auditor_id:params.CurUserGUID,auditor_code:params.CurUserCode,auditor_name:params.CurUserName}]));
        return null;
    }
    else
    {
        console.warn("字段 ‘" + cell.name + "’ 的值有误，重置为空数组，错误值：", defaultValue);
        if(Array.isArray(defaultValue)){//如果默认值是数组
          fieldConfig.onChange(JSON.stringify(defaultValue));
          return null;
        }else{//其他情况转为空数组（比如对象类型，会导致组件出错）
          defaultValue = [];
        }
    }

  }else{
    defaultValue = parseToArray(defaultValue);//转为数组
  }

  if (isDisplay) {
    //返回实际显示的文本
    function getDataText(value) {
      var txts = [];
      value.forEach(function (item) {
        txts.push(item.auditor_name);
        //personCode.push(item.auditor_id || item.id);发送组织信息需要的参数
      });
      return txts.join(",");
    }
    return getDataText(defaultValue);
  }

  //编辑模式
  let component = <SelectAuditors
                        className={className}
                        placeholder={cell?.designProps?.text? cell?.designProps?.text:"请选择"}
                        onChange={(data)=>{
                            fieldConfig.onChange(JSON.stringify(data));
                            fieldConfig.onBlur(JSON.stringify(data));
                        }}
                        multiSelect={false}
                        filterDisable={false}
                        textField={"auditor_name"}
                        valueField={"auditor_id"}
                        // width="80px"
                        value={defaultValue}
                        title={cell.name}
                    ></SelectAuditors>
           
  return component;
}

